<template>
  <van-button
    v-if="isFollowed"
    round
    :loading="followLoading"
    size="small"
    @click="onFollow"
  >
    已关注
  </van-button>
  <van-button
    v-else
    type="info"
    color="#3296fa"
    round
    size="small"
    icon="plus"
    :loading="followLoading"
    @click="onFollow"
  >
    关注
  </van-button>
</template>

<script>
import { addFollow, deleteFollow } from '@/api/user'

export default {
  name: 'FollowUser',
  model: {
    prop: 'isFollowed', // 默认是 value
    event: 'update-followed' // 默认是 input
  },
  props: {
    authorId: {
      type: [Number, String, Object],
      required: true
    },
    isFollowed: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      followLoading: false
    }
  },
  methods: {
    async onFollow() {
      this.followLoading = true
      try {
        if (this.isFollowed) {
          // 已关注 取消关注
          await deleteFollow(this.authorId)
          this.$toast('取消关注成功')
        } else {
          // 未关注 添加关注
          await addFollow(this.authorId)
          this.$toast('关注成功')
        }
        // 更新视图
        this.$emit('update-followed', !this.isFollowed)
      } catch (error) {
        let msg = '操作失败,请稍后重试！'
        if (error.response && error.response.status === 400) {
          msg = '不能关注自己哟！'
        }
        this.$toast(msg)
      }
      this.followLoading = false
    }
  }
}
</script>

<style lang="less" scoped></style>
